package org.example.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * @author 邓天天
 * @date 2021/4/5 8:23
 */
public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int port = 10009;

    /**
     * 构造器，初始化工作
     */
    public GroupChatServer() {
        try{
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.configureBlocking(false);
            // 绑定监听某一个端口
            listenChannel.bind(new InetSocketAddress(port));
            // 注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException exception) {
            exception.printStackTrace();
        }

    }
    public void listen() {
        try{
            // 是否有监听时间
            while (selector.select()>0) {
                final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    final SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()) {
                        final SocketChannel socketChannel = listenChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector,SelectionKey.OP_READ);
                        System.out.println(socketChannel.getRemoteAddress() + "上线");
                    }
                    if (selectionKey.isReadable()) {
                        // 处理读
                        readDate(selectionKey);
                    }
                    iterator.remove();
                }
            }
        }catch (IOException e) {e.printStackTrace();}
    }
    private void readDate(SelectionKey selectionKey) {
        SocketChannel channel = null;
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            channel = (SocketChannel) selectionKey.channel();
            while (channel.read(buffer) != -1) {
                String msg = new String(buffer.array());
                System.out.println("from 客户段"+msg);
                // 向其他客户段转发消息
                sendInfoToOtherClients(msg,channel);
            }
            buffer.clear();
        }catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + "离线了，，，");
                // 取消通道
                selectionKey.cancel();
                channel.close();
            } catch (IOException exception){
                e.printStackTrace();
            }

        }
    }

    /**
     * 转发消息给其他客户段
     * @param msg
     * @param self
     * @throws IOException
     */
    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException{
        System.out.println("服务器转发消息中，，，，");
        for (SelectionKey key: selector.keys()) {
            // 通过key 取出对应的SocketChannel
            Channel targetChannel = key.channel();

            // 排除自己
            if (targetChannel instanceof SocketChannel &&  targetChannel != self) {
                SocketChannel dest = (SocketChannel) targetChannel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
                dest.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }

}
